//
//  CustomView.m
//  jmGouTong
//
//  Created by 王大虎 on 2022/9/23.
//  Copyright © 2022 seclery. All rights reserved.
//

#import "CustomView.h"
#import <JitsiMeetSDK/JitsiMeetView.h>
#import <Masonry.h>

@interface CustomView ()<JitsiMeetViewDelegate>
@property (nonatomic, strong) JitsiMeetView *jitsiMeetView;
@property (nonatomic, strong) NSDate *initialTime;
@property (nonatomic, assign) NSInteger numberOfOtherParticipantsInCall;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) BOOL isTimeLabelAlreadyAdded;

@property (nonatomic, strong) UILabel *callingLabel;
@property (nonatomic, strong) UILabel *timeLabel;
//@property (nonatomic, strong) Pip
@end
@implementation CustomView


-(UILabel *)callingLabel{
    if (!_callingLabel) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectZero];
        label.translatesAutoresizingMaskIntoConstraints = NO;
        label.textColor = UIColor.yellowColor;
        label.font = [UIFont systemFontOfSize:12];
        label.text = @"CALLING....";
        label.backgroundColor = UIColor.clearColor;
        label.textAlignment = NSTextAlignmentCenter;
        _callingLabel = label;
    }
    return _callingLabel;
}

-(UILabel *)timeLabel{
    if (!_timeLabel) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectZero];
        label.translatesAutoresizingMaskIntoConstraints = NO;
        label.textColor = UIColor.yellowColor;
        label.font = [UIFont systemFontOfSize:12];
        label.text = @"00:00";
        label.backgroundColor = UIColor.clearColor;
        label.textAlignment = NSTextAlignmentCenter;
        _timeLabel = label;
    }
    return _timeLabel;
}


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}

-(void)joinMeet{
    JitsiMeetView *jitsiMeetView = [[JitsiMeetView alloc]initWithFrame:self.bounds];
    jitsiMeetView.delegate = self;
    [self addSubview:jitsiMeetView];
    
    self.jitsiMeetView = jitsiMeetView;
    
    if (self.call == nil) {
        return;
    }
    
    NSString *subject = self.call.outgoing ? @"111" : @"2222";
    
    NSString *displayName = self.call.outgoing ? @"aaaa":@"bbb";
    
    JitsiMeetConferenceOptions *options = [JitsiMeetConferenceOptions fromBuilder:^(JitsiMeetConferenceOptionsBuilder * builder) {
        [builder setCallUUID:self.call.uuid];
        [builder setCallHandle:@"Dummy SSF App"];
        [builder setVideoMuted:self.call.isAudioCall];
        [builder setRoom:self.roomName];
        [builder setSubject:subject];
        JitsiMeetUserInfo *userInfo = [[JitsiMeetUserInfo alloc]init];
        userInfo.displayName = displayName;
        builder.userInfo = userInfo;
    }];
    [self.jitsiMeetView join:options];
}

-(void)endCallManuallyWithEndCallReason:(CXCallEndedReason)reason{
    [self hideCallingLabelStopRiningSound];
    [self.jitsiMeetView hangUp];
    [self cleanUp];
    
    Call *getCall = [self.callManager callWithUUID:self.call.uuid];
    if (getCall) {
        [self.callManager end:getCall];
    }
    
}

-(void)hideCallingLabelStopRiningSound {
    
    [self.callingLabel setHidden:YES];
    
    [self.player stop];
    self.player = nil;

}


-(void)startTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
}

-(void)addCallingLabel{
    [self.jitsiMeetView addSubview:self.callingLabel];
    [self.callingLabel setHidden:NO];
    [self.callingLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.topMargin.mas_lessThanOrEqualTo(self).offset(100);
        make.leading.equalTo(self);
        make.trailing.equalTo(self);
        make.height.mas_equalTo(50);
    }];
    [self playSound];
}

-(void)playSound{
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"voip_call" withExtension:@"caf"];
    
    NSError *setCategoryErr = nil;
    NSError *setModeErr = nil;
    NSError *activationErr  = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error: &setCategoryErr];
    [[AVAudioSession sharedInstance] setMode:AVAudioSessionModeVoiceChat error:&setModeErr];
    [[AVAudioSession sharedInstance] setActive:YES error:&activationErr];
    
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url fileTypeHint:AVFileTypeMPEGLayer3 error:nil];
    [_player play];
}

-(void)addTimeLabel{
    if (self.isTimeLabelAlreadyAdded) {
        return;
    }
    [self.jitsiMeetView addSubview:self.timeLabel];
    self.isTimeLabelAlreadyAdded = YES;
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.topMargin.lessThanOrEqualTo(self).offset(50);
        make.leading.equalTo(self);
        make.trailing.equalTo(self);
        make.height.mas_equalTo(50);
    }];
    
    [self.timeLabel setHidden:YES];
}

-(void)cleanUp{
    [self.jitsiMeetView removeFromSuperview];
    self.numberOfOtherParticipantsInCall = 0;
    [self.timer invalidate];
    self.timer = nil;
    self.initialTime = nil;
    self.timeLabel.text = nil;
    self.isTimeLabelAlreadyAdded = NO;
    self.jitsiMeetView = nil;
}

#pragma mark -JitsiMeetViewDelegate

- (void)conferenceTerminated:(NSDictionary *)data{
    [self endCallManuallyWithEndCallReason:CXCallEndedReasonRemoteEnded];
    
}

- (void)conferenceJoined:(NSDictionary *)data{
    if (self.call.outgoing) {
        [self addCallingLabel];
    }
    [self addTimeLabel];
    
}

- (void)participantJoined:(NSDictionary *)data{
    
}

- (void)participantLeft:(NSDictionary *)data{
    self.numberOfOtherParticipantsInCall -= 1;
    
    if (self.numberOfOtherParticipantsInCall == 0) {
        [self endCallManuallyWithEndCallReason:CXCallEndedReasonRemoteEnded];
    }
}

-(void)updateTime{
//    self.initialTime = [NSDate new];
    
    self.timeLabel.text = @"1111";
    
}




@end
